// pages/individual/index.js
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		myWords: [],
		mySentences: [],
		recentWords: [],
		// 0 暗黑模式 1 明亮模式
		mode: 0,
		avatarUrl: ''
	},

	editMySentence(e) {
		wx.showActionSheet({
			itemList: ['update', 'delete'],
			success(res) {
				if (res.tapIndex === 0) {
					wx.navigateTo({
						url: `../edit_s/index?params=${JSON.stringify(
							e.currentTarget.dataset
						)}`,
					})
				} else {
					wx.showToast({
						title: 'NOT OPEN',
						icon: 'error',
					})
				}
			},
		})
	},

	toAllMyWords() {
		wx.navigateTo({
			url: '../all_words/index',
		})
	},

	randomAvatar() {
		const avatarIndex = Math.ceil(Math.random() * 8)
		wx.setStorageSync('avatar-index', avatarIndex)
		this.setData({ avatarUrl: `../../images/test-avatar0${avatarIndex}.svg` })
	},

	toggleVisionMode() {
		const vmode = this.data.mode
		this.setData({ mode: vmode ? 0 : 1 })
		wx.setStorageSync('vision-mode', this.data.mode)
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function () {
		if (!wx.getStorageSync('avatar-index'))
			wx.setStorageSync('avatar-index', '1')
		const avatarIndex = wx.getStorageSync('avatar-index')
		this.setData({ avatarUrl: `../../images/test-avatar0${avatarIndex}.svg`})
		wx.showLoading({
			title: 'Loading...',
		})
		wx.cloud
			.callFunction({
				name: 'getMyWord',
			})
			.then(res => {
				this.setData({
					myWords: res.result.data,
					recentWords: res.result.data.slice(-3),
				})
			})
		wx.cloud
			.callFunction({
				name: 'getMySentence',
			})
			.then(res => {
				this.setData({ mySentences: res.result.data })
				wx.hideLoading()
			})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		let mode = null
    const store = parseInt(wx.getStorageSync('vision-mode'))
    if (isNaN(store)) {
      mode = 1
    } else {
      mode = store
    }
    this.setData({ mode })
		wx.showLoading({
			title: 'Loading...',
		})
		wx.cloud
			.callFunction({
				name: 'getMyWord',
			})
			.then(res => {
				this.setData({
					myWords: res.result.data,
					recentWords: res.result.data.slice(-3),
				})
			})
		wx.cloud
			.callFunction({
				name: 'getMySentence',
			})
			.then(res => {
				this.setData({ mySentences: res.result.data })
				wx.hideLoading()
			})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {},
})
